import { _decorator, Component, Node, Vec2, director, Prefab,instantiate, UITransform } from 'cc';
import { GameData, GameState } from './GameData';

import { Plant } from './Plant';
import { ZombiesLayer } from './ZombiesLayer';
const { ccclass, property } = _decorator;
const gameData = GameData.getInstance()

@ccclass('Pease')
export class Pease extends Plant {
    zombieLayer = null;

    bulletLayer = null;

    attackRange = 1000

    @property(Prefab)

    bullet = null;

    onLoad() {
        this.zombieLayer = director.getScene().getChildByPath('Canvas/mainNode/zombieLayer').getComponent(ZombiesLayer);

        this.bulletLayer = director.getScene().getChildByPath('Canvas/mainNode/bulletLayer');
    }

    update(deltaTime: number) {
        // 每帧调用，用于更新植物的攻击计时器
        if(this.isAlive && gameData.gameSate === GameState.ready) {
            this.tryAttack()
        }
        this.updateAttackTimer(deltaTime);
    }

    updateAttackTimer(dt: number) {
        if (this.attackTimer > 0) {
            this.attackTimer -= dt;
        }
    }

    tryAttack() {
        if (this.attackTimer <= 0) {
            // 执行攻击逻辑
            this.findAndAttackZombies();
            this.attackTimer = this.attackCooldown; // 重置攻击计时器
        }
    }

    findAndAttackZombies() {
        // 发射子弹
        let zombies = this.findZombiesInRange(this.attackRange);
        if(zombies.length){
            this.createBullet()
        }
    }
    createBullet() {
        // 实例化子弹
        let bullet = instantiate(this.bullet);
        const p = this.bulletLayer.getComponent(UITransform).convertToNodeSpaceAR(this.node.worldPosition)
        p.y += 20;
        p.x += 40;
        // 设置位置
        bullet.setPosition(p);
        // 添加到场景中
        this.bulletLayer.addChild(bullet);
    }
    attackZombie(zombie) {
        // 减少僵尸的生命值
        zombie.takeDamage(this.attackDamage);
    }
    findZombiesInRange(range) {
        let zombies = [];
        // 有一个函数 getAllZombies 返回场景中所有的僵尸
        let allZombies = this.zombieLayer.getAllZombies();
        for (let zombie of allZombies) {
            if (this.isZombieInRange(zombie, range)) {
                zombies.push(zombie);
            }
        }
        return zombies;
    }
    
    isZombieInRange(zombie, range) {
        // 计算植物和僵尸之间的距离
        let distance = Vec2.distance(this.node.worldPosition, zombie.worldPosition);
        return distance <= range;
    }
}


